package edu.csula.cs575;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class SOS<CalendarView> extends Activity {
	ListView contactList;
	ListView emailList;
	ImageButton backButton;
	ImageButton SMSButton;
	ImageButton EditLocation;
	ImageButton EmailButton;
	ImageButton hideButton;
	ImageButton contactlistbutton;
	ImageButton emaillistbutton;
	ArrayList<CantactView> cVArrayList;
	ArrayList<CantactView> cVArrayListChecked;
	ArrayList<EmailView> cVArrayList2;
	ArrayList<EmailView> cVArrayListChecked2;
	EditText phoneNumber;
	EditText emailAddress;
	EditText msgBody;
	EditText emailBody;
	EditText editLocationText;
	Button addButton;
	Button addClear;
	Button addCancel;
	Button editCancel;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smssender);
        populatebackButton();
        populateContactList();
        populateAddContact();
        populateEmailList();
        populateAddEmail();
        populateEditLocationBtn();
        populateSendSMSButton();
        phoneNumber = (EditText) findViewById(R.id.phoneNumber);
        phoneNumber.requestFocus();      
        phoneNumber.postDelayed(new Runnable() {
             public void run() {
                 InputMethodManager keyboard = (InputMethodManager)
                 getSystemService(Context.INPUT_METHOD_SERVICE);
                 keyboard.showSoftInput(phoneNumber, 0);
             }
         },200);
    }
   private void populateEditLocationBtn() {
	   
		EditLocation = (ImageButton) findViewById(R.id.edit_location_button);
		EditLocation.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
		final Dialog dlg1 = new Dialog(SOS.this);
		LayoutInflater li = (LayoutInflater) SOS.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v1 = li.inflate(R.layout.edit_location, null, false);
		dlg1.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dlg1.setContentView(v1);
		dlg1.show();
		editLocationText = (EditText) dlg1.findViewById(R.id.edit_location_text);
		editLocationText.setText("I am at: \n");
        addButton = (Button) dlg1.findViewById(R.id.editbutton);
        addButton.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			dlg1.dismiss();	
    		}
		});
        editCancel = (Button) dlg1.findViewById(R.id.cancelbutton);
        editCancel.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			
    			dlg1.dismiss();
    		}
		});
    	}
		});
	}

	private void populateAddContact() {
		SMSButton = (ImageButton) findViewById(R.id.contactlistbutton);
    	SMSButton.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			final ArrayList<CantactView> templist = new  ArrayList<CantactView>(cVArrayList);
    			templist.clear();
    			for(CantactView item: cVArrayList) templist.add(item);
    			final ArrayList<CantactView> templistChecked = new  ArrayList<CantactView>(cVArrayListChecked);
    		

    			final Dialog dlg = new Dialog(SOS.this);
    			LayoutInflater li = (LayoutInflater) SOS.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			View v1 = li.inflate(R.layout.contact_list, null, false);
    			dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
    			dlg.setContentView(v1);
				contactList = (ListView) dlg.findViewById(R.id.contactlist);

				contactList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				contactList.setClickable(true);
				 final ArrayAdapter<CantactView> adpr = new CantactViewAdaptor(SOS.this, R.layout.contactentry, cVArrayList) ;
		        contactList.setAdapter(adpr);
		        contactList.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {

						CheckBox cBox = (CheckBox) view.findViewById(R.id.checkBoxCheck);
						cBox.toggle();
						cVArrayList.get(position).setChecked(cBox.isChecked());
						cVArrayListChecked.add(cVArrayList.get(position));
						
					}
				});
		        dlg.show();
		        addButton = (Button) dlg.findViewById(R.id.addbutton);
		        addButton.setOnClickListener(new View.OnClickListener() {
		    		public void onClick(View v) {
		    			
		    			dlg.dismiss();	
		    		}
				});
		        addClear = (Button) dlg.findViewById(R.id.clearbutton);
		        addClear.setOnClickListener(new View.OnClickListener() {
		    		public void onClick(View v) {
		    			cVArrayListChecked.clear();
		    			cVArrayList.clear();
		    			populateContactList();
		    			dlg.dismiss();
		    		}
				});
		        addCancel = (Button) dlg.findViewById(R.id.cancelbutton);
		        addCancel.setOnClickListener(new View.OnClickListener() {
		    		public void onClick(View v) {
		    			/*cVArrayList.clear();
		    			for(CantactView item: templist) cVArrayList.add(item);
		    			cVArrayListChecked = templistChecked;*/
		    			dlg.dismiss();
		    		}
				});
		    		}
		    		});
	}
	private void populateContactList() {
			

				String[] l_projection = new String[] { Phone.DISPLAY_NAME,
						Phone.NUMBER };

				Cursor cursor = getContentResolver().query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						l_projection, null, null, "display_name ASC");
				cVArrayList = new ArrayList<CantactView>();
				cVArrayListChecked = new ArrayList<CantactView>();

				int colName;
				String name;
				int colNumber;
				String number;
				for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
						.moveToNext()) {

					CantactView cV = new CantactView();
					colName = cursor.getColumnIndex(l_projection[0]);
					name = cursor.getString(colName);
					// Log.d("This is to show the l_title: ", l_title + "" );

					colNumber = cursor.getColumnIndex(l_projection[1]);
					number = cursor.getString(colNumber);

					cV.setName(name);
					cV.setNumber(number);
					cVArrayList.add(cV);

					// }
				}
	}
	
	private void populateAddEmail() {
		EmailButton = (ImageButton) findViewById(R.id.emaillistbutton);
		EmailButton.setOnClickListener(new View.OnClickListener() {
		public void onClick(View v) {
			final ArrayList<EmailView> templist2 = new ArrayList<EmailView>(cVArrayList2);
			final ArrayList<EmailView> templistChecked2 = new  ArrayList<EmailView>(cVArrayListChecked2);
		
    		

			final Dialog dlg = new Dialog(SOS.this);
			LayoutInflater li = (LayoutInflater) SOS.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View v1 = li.inflate(R.layout.email_list, null, false);
			dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dlg.setContentView(v1);
			emailList = (ListView) dlg.findViewById(R.id.emaillist);
	    	emailList.setItemsCanFocus(false);
	    	emailList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    	emailList.setClickable(true);
	    	emailList.setTextFilterEnabled(true);
	    	dlg.show();
	    	if (!cVArrayList2.isEmpty()){
	            ArrayAdapter<EmailView> adpr = new EmailViewAdaptor(SOS.this, R.layout.emailentry, cVArrayList2) ;
	            emailList.setAdapter(adpr);
	            emailList.setOnItemClickListener(new OnItemClickListener() {

	    			public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {

	    				CheckBox cBox = (CheckBox) view.findViewById(R.id.checkBoxCheck2);
	    				cBox.toggle();
	    				cVArrayList2.get(position).setChecked(cBox.isChecked());
	    				cVArrayListChecked2.add(cVArrayList2.get(position));
	    				
	    			}
	    		});
	            }
	        addButton = (Button) dlg.findViewById(R.id.addbutton);
	        addButton.setOnClickListener(new View.OnClickListener() {
	    		public void onClick(View v) {
	    			dlg.dismiss();	
	    		}
			});
	        addClear = (Button) dlg.findViewById(R.id.clearbutton);
	        addClear.setOnClickListener(new View.OnClickListener() {
	    		public void onClick(View v) {
	    			cVArrayListChecked2.clear();
	    			populateEmailList();
	    			dlg.dismiss();
	    		}
			});
	        addCancel = (Button) dlg.findViewById(R.id.cancelbutton);
	        addCancel.setOnClickListener(new View.OnClickListener() {
	    		public void onClick(View v) {
	    			cVArrayList2 = templist2;
	    			cVArrayListChecked2 = templistChecked2;
	    			dlg.dismiss();
	    		}
			});
	    		}
	    		});
	        
	
}
	private void populateEmailList() {
		
		
    	
    	
    	String[] l_projection = new String[] {Email.DATA};
    	Cursor cursor = getContentResolver().query(
    			ContactsContract.CommonDataKinds.Email.CONTENT_URI,l_projection 
    			, null, null, "data1 ASC");
    	cVArrayList2 = new ArrayList<EmailView>();
    	cVArrayListChecked2 = new ArrayList<EmailView>();
        
        
    	int colName;
    	String email;
    	for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

			
			EmailView cV2 = new EmailView();
			colName = cursor.getColumnIndex(l_projection[0]);
			email = cursor.getString(colName);
			//Log.d("This is to show the l_title: ", l_title + "" );

			
				if(email != null && !email.equals("")){
						cV2.setEmail(email);
						cVArrayList2.add(cV2);
				}
			
			//}
		}

	}

	private void populatebackButton() {
    	backButton = (ImageButton) findViewById(R.id.backbutton);
    	backButton.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			
    			Intent mainIntent = new Intent(SOS.this, MainPage.class);
    			setResult(RESULT_OK, mainIntent);
    			overridePendingTransition(R.anim.zoom_exit, R.anim.hold);
    			finish();
    		}

    	});
    }
    class DoneOnEditorActionListener implements OnEditorActionListener {
        
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return true;	
            }
            return false;
        }
    }
private void populateSendSMSButton() {
    	
    	phoneNumber = (EditText) findViewById(R.id.phoneNumber);
    	msgBody = (EditText) findViewById(R.id.editSMSText);
    	SMSButton = (ImageButton) findViewById(R.id.sendbutton);
    	SMSButton.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			Toast.makeText(getApplicationContext(), phoneNumber.getText().toString() + msgBody.getText().toString(),
						Toast.LENGTH_LONG).show();
    			for(CantactView contact:cVArrayListChecked){
    				
    			try {
    				
    				//SmsManager smsManager = SmsManager.getDefault();
    				//smsManager.sendTextMessage(contact.getNumber(), null, "test", null, null);
    				Toast.makeText(getApplicationContext(), contact.getNumber()+" : "+msgBody.getText().toString(),
    							Toast.LENGTH_LONG).show();
    			  } catch (Exception e) {
    				Toast.makeText(getApplicationContext(),
    					"SMS faild, please try again later!",
    					Toast.LENGTH_LONG).show();
    				e.printStackTrace();
    			  }
    			}
    			for(EmailView email:cVArrayListChecked2){
    				
        			
        			try {
        				
        				//SmsManager smsManager = SmsManager.getDefault();
        				//smsManager.sendTextMessage(contact.getNumber(), null, "test", null, null);
        				Toast.makeText(getApplicationContext(), email.getEmail()+" : "+msgBody.getText().toString(),
        							Toast.LENGTH_LONG).show();
        			  } catch (Exception e) {
        				Toast.makeText(getApplicationContext(),
        					"Email faild, please try again later!",
        					Toast.LENGTH_LONG).show();
        				e.printStackTrace();
        			  }
        			}
    		}
    		});
	}
    

	
}